﻿using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class AdministratorsPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IAdministratorsView _view;
        
        public AdministratorsPresenter(IAdministratorsView view)
            : this(view, new RepositoryFactory())
        {
        }

        public AdministratorsPresenter(IAdministratorsView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.Administrators)
            {
                _view.RedirectToPermissionDeniedPage();
            }
        }

        public void Initialize()
        {
            SetAdministrators();
        }
        
        public void SetAdministrators()
        {
            _view.SetAdministrators(AdministratorRepository.GetAdministrators());
        }

        public void Delete(int id)
        {
            Administrator admin = AdministratorRepository.GetAdministrator(id);
            if (AdministratorRepository.GetAdministrators().Count <= 1)
            {
                _view.DeleteLastAdministratorAlert(admin.Fullname);
                return;
            }
            if (admin.Group.ID == 1) 
            {
                // Administrators group
                bool moreThanOneAdminLeft = false;
                foreach (Administrator a in AdministratorRepository.GetAdministrators())
                {
                    if (a.ID != id && a.Group.ID == 1)
                    {
                        moreThanOneAdminLeft = true;
                    }
                }
                if (!moreThanOneAdminLeft)
                {
                    _view.DeleteLastAdministratorInTheAdminGroupAlert(admin.Fullname);
                    return;
                }
            }
            admin.Deleted = true;
            AdministratorRepository.SaveAdministrator(admin);
            SetAdministrators();
        }
    }
}